<template>
  <!-- 学生页面 -->
  <el-container class="h-full">
    <el-header class="border-b border-gray-200">
      <div class="w-full h-full flex justify-between items-center">
        <div class="text-xl font-bold">学生教辅平台</div>
        <div class="flex items-center gap-4">
          <div class="text-base font-bold">{{ userInfo.name }}</div>
          <el-button type="primary" size="small" @click="logout"
            >退出登录</el-button
          >
        </div>
      </div>
    </el-header>
    <el-container>
      <el-aside width="200px" class="border-r border-gray-200">
        <el-menu
          :default-active="activeMenu"
          class="h-full"
          @select="handleMenuSelect"
        >
          <el-menu-item index="courses">
            <el-icon><VideoPlay /></el-icon>
            <span>课程视频</span>
          </el-menu-item>
          <el-menu-item index="attendance">
            <el-icon><Calendar /></el-icon>
            <span>签到记录</span>
          </el-menu-item>
          <el-menu-item index="assignments">
            <el-icon><Files /></el-icon>
            <span>作业记录</span>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-main>
        <!-- 课程视频区域 -->
        <div v-if="activeMenu === 'courses'" class="courses-container">
          <h2 class="text-xl font-bold mb-4">课程视频</h2>
          <el-row :gutter="20">
            <el-col v-for="course in courseList" :key="course.id" :span="8">
              <el-card class="mb-4 cursor-pointer">
                <div
                  v-for="file in course.files"
                  :key="file.fileUrl"
                >
                <div
                  @click="viewCourse(course, file.fileUrl)"
                >
                <video :src="file.fileUrl"></video>
                </div>
               
                  <div class="text-lg font-bold">{{ course.name }}</div>
                  <el-button class="flex-1 w-full" type="primary" @click="viewCourseHomework(course)">
                     课堂作业
                 </el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
        <!-- 签到记录区域 -->
        <div v-if="activeMenu === 'attendance'" class="attendance-container">
          <Sign2 />
        </div>

        <!-- 作业管理区域 -->
        <div v-if="activeMenu === 'assignments'" class="assignments-container">
          <Sign :data="courseList" />
        </div>
      </el-main>
    </el-container>
  </el-container>

  <!-- 查看课程视频对话框 -->
  <el-dialog v-model="courseDialogVisible" title="课程视频" width="800px">
    <div v-if="currentCourse">
      <h2 class="text-xl font-bold mb-2">{{ currentCourse.name }}</h2>
      <div
        class="video-player bg-black h-[400px] mb-4 flex justify-center items-center"
      >
        <video
          controls
          class="w-full h-full"
          :src="currentCourse.videoUrl"
        ></video>
      </div>
    </div>
  </el-dialog>
    <!-- 查看课程视频对话框 -->
    <el-dialog v-model="courseHomeWorkDialogVisible" title="课程作业" width="800px">
    <div v-if="currentCourse">
      <h2 class="text-xl font-bold mb-2">{{ currentCourse.name }}</h2>
      <template v-if="homework.length > 0">
        <div
          v-for="item in homework"
          class="w-full flex flex-col gap-4 p-4 rounded-md mb-4"
          style="border: 1px solid #ccc"
          :key="item.id"
        >
          <div
            v-for="(file, i) in item.files"
            class="w-full flex items-center gap-4"
            :key="i"
          >
            <span>{{ file.name }}</span>
            <el-button type="primary" @click="downloadHomework(file.fileUrl)">
              下载
            </el-button>
          </div>

          <div
            v-if="item.stuHomeworks && item.stuHomeworks.length > 0"
            class="flex flex-col gap-4"
          >
            <div v-for="(list, i) in item.stuHomeworks" :key="i">
              <h3 class="text-lg font-bold mb-2">学生作业列表</h3>
              <div class="">
                <div class="">作业描述: {{ list.des }}</div>
                <div
                  class="cursor-pointer text-blue-600"
                  title="点击预览"
                  @click="viewDoc(list.studentHomeworkFiles?.[0].fileUrl)"
                >
                  {{ list.studentHomeworkFiles?.[0].name }}
                </div>
              </div>
              <div class="mb-2 flex flex-col gap-2 mt-2">
                <div>作业评审:</div>
                <textarea
                  v-model="list.feedback"
                  style="border: 1px solid #ccc"
                  class="w-full h-[50px] p-4"
                ></textarea>
                <div>
                  <span>成绩</span>
                  <el-input 
                  type="number"
                  min="0"
                  max="100"
                  oninput="if(value>100)value=100;if(value<0)value=0"
                  v-model="list.score"></el-input>
                </div>
                <el-button @click="submitFeedback(list, item)"
                  >提交评审</el-button
                >
              </div>
            </div>
          </div>
          <el-button @click="getHomeworkByCourseHomeworks(item)">
            作业互评
          </el-button>

          <div class="flex flex-col gap-4">
            <h3 class="text-lg font-bold mb-2">作业描述</h3>
            <textarea
              v-model="item.desc"
              rows="5"
              class="p-4"
              style="border: 1px solid #ccc"
            ></textarea>
            <div v-if="item.file" class="flex items-center justify-between">
              <span>{{ item.file.name }}</span>
              <el-button type="danger" @click="item.file = null">
                删除
              </el-button>
            </div>
            <el-button
              class="w-full"
              type="primary"
              @click="handleUploadHomeFile(item)"
            >
              点击上传作业
            </el-button>
            <el-button
              class="w-full !m-0"
              type="primary"
              @click="handleSubmitHome(item)"
            >
              点击提交作业
            </el-button>
          </div>
        </div>
      </template>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import {
  Document,
  ChatDotRound,
  Calendar,
  DataAnalysis,
  Files,
  VideoPlay,
} from "@element-plus/icons-vue";
import { useProject, type Course } from "../teacher/composables/useProject";
import { request } from "../../utils/request";
import {
  correctHomework,
  getCourseHomework,
  getHomeworkByCourseHomeworkId,
  getHomeworkByCourseHomeworkIdAndStatus,
  studentSubmitHomework,
} from "../../api/modules/course";
import { downloadFile } from "../../api/modules/file";
import { useUserStore } from "../../store/user";
import Sign from "./components/Sign.vue";
import Sign2 from "./components/Sign2.vue";

const router = useRouter();
const activeMenu = ref("courses");

const { courseList, getCourseList } = useProject();
getCourseList("");

const userStore = useUserStore();
const userInfo = computed(() => userStore.userInfo.value);

// 课程列表
const courses = ref([
  { id: 1, title: "高等数学", teacher: "李教授", thumbnail: "" },
  { id: 2, title: "大学物理", teacher: "王教授", thumbnail: "" },
  { id: 3, title: "计算机基础", teacher: "赵教授", thumbnail: "" },
]);

// 作业列表
const assignments = ref([]);

const activeCourse = ref("");
const signForm = reactive({
  courseId: "",
});

function getSign() {
  assignments.value = [];
}

// 签到记录
const activeAttendance = ref({
  id: 1,
  course: "高等数学",
  endTime: "2023-10-10 10:30",
  signed: false,
});

// 成绩列表
const grades = ref([
  {
    id: 1,
    course: "高等数学",
    assignment: "高数作业一",
    score: 90,
    feedback: "做得不错，继续努力！",
  },
  {
    id: 2,
    course: "大学物理",
    assignment: "物理实验报告",
    score: 85,
    feedback: "实验数据分析有待提高",
  },
  {
    id: 3,
    course: "计算机基础",
    assignment: "计算机编程作业",
    score: 95,
    feedback: "代码结构清晰，逻辑严谨",
  },
]);

// 提交作业相关
const assignmentDialogVisible = ref(false);
const currentAssignment = ref(null);
const assignmentForm = reactive({
  content: "",
  files: [],
});

// 批改作业相关
const reviewDialogVisible = ref(false);
const currentReview = ref(null);
const reviewForm = reactive({
  score: 0,
  feedback: "",
});

// 查看课程视频相关
const courseDialogVisible = ref(false);
const courseHomeWorkDialogVisible = ref(false);
const currentCourse = ref<any>(null);

// 菜单选择
function handleMenuSelect(key) {
  activeMenu.value = key;
}

// 退出登录
function logout() {
  localStorage.removeItem("token");
  router.push("/login");
}

// 提交作业
function submitAssignment(assignment) {
  currentAssignment.value = assignment;
  assignmentForm.content = "";
  assignmentForm.files = [];
  assignmentDialogVisible.value = true;
}

const homework = ref<any[]>([]);
function getHomework(id: string) {
  request({
    fn: getCourseHomework,
    params: [id],
    success(res) {
      homework.value = res.data;
      homework.value.forEach((item) => {
        item.homeworks = {
          desc: "",
          file: "",
        };
      });
    },
  });
}

function downloadHomework(url: string) {
  console.log(url);
  downloadFile(url).then((res) => {
    const blob = new Blob([res as any]);
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = url;
    link.click();
  });
}

// 查看课程
function viewCourse(course: Course, file: string) {
  // 设置当前课程，添加视频和课件信息
  currentCourse.value = {
    ...course,
    videoUrl: file,
  };

  getHomework(course.id.toString());

  // 显示课程视频对话框
  courseDialogVisible.value = true;
}

// 查看课程作业
function viewCourseHomework(course: Course) {
  // 设置当前课程，添加视频和课件信息
  currentCourse.value = {
    ...course,
  };

  getHomework(course.id.toString());

  // 显示课程视频对话框
  courseHomeWorkDialogVisible.value = true;
}

function handleUploadHomeFile(item: any) {
  const input = document.createElement("input");
  input.type = "file";
  input.multiple = true;
  input.accept = "*.doc,.docx";
  input.onchange = (e: any) => {
    const file = e.target.files?.[0];
    if (!file) return;
    item.file = file;
  };
  input.click();
}
function handleSubmitHome(item: any) {
  if (!item.file) {
    ElMessage.warning("请选择文件");
    return;
  }
  if (!item.desc) {
    ElMessage.warning("请输入作业描述");
    return;
  }
  const formData = new FormData();
  formData.append("file", item.file);
  formData.append("desc", item.desc);
  formData.append("courseHomeworkId", item.id);

  request({
    fn: studentSubmitHomework,
    params: [formData],
    success() {
      ElMessage.success("提交成功");
      item.file = null;
      item.desc = "";
    },
  });
}

// 查询课程作业
function getHomeworkByCourseHomeworks(item: any) {
  request({
    fn: getHomeworkByCourseHomeworkIdAndStatus,
    params: [item.id],
    success(res) {
      item.stuHomeworks = res.data ? [res.data] : [];
      if (item.stuHomeworks.length === 0) {
        ElMessage.warning("暂无作业");
      }
    },
  });
}

function viewDoc(url) {
  window.open(`/preview?url=${url}`, "_blank");
}

function submitFeedback(list: any, item) {
  console.log(list);
  if (list.feedback === "") {
    ElMessage.warning("请输入评审内容");
    return;
  }
  if (!list.score) {
    ElMessage.warning("请输入评分");
    return;
  }
  request({
    fn: correctHomework,
    params: [
      {
        grades: list.score,
        comments: list.feedback,
        studentHomeworkId: list.id,
      },
    ],
    success() {
      ElMessage.success("提交成功");
      item.stuHomeworks = null;
    },
  });
}

</script>

<style scoped>
.el-header {
  height: 60px;
  line-height: 60px;
}

.el-aside {
  background-color: #fff;
}

.el-main {
  padding: 20px;
  background-color: #f5f7fa;
}
</style>
